<template>
    <el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
        textAlign: 'center',
        background: '#f5f7fa',
        fontWeight: 'bold',
        position: 'sticky',
        top: 0
    }" :span-method="objectSpanMethod">
        <el-table-column fixed width="180px" prop="sale_Order_Code" label="退货编号">
            <template #default="scope">
                <el-link type="primary" @click="infoPage(scope.row.sale_Return_Code)">{{ scope.row.sale_Return_Code
                }}</el-link>
            </template>
        </el-table-column>
        <el-table-column fixed width="180px" prop="sale_Return_Status" label="订单状态" />
        <!-- <el-table-column fixed width="180px" prop="sale_Return_Audit_Status" label="审核状态">
            <template #default="scope">
                <span>{{ scope.row.sale_Return_Audit_Status == '0' ? "待审核" : scope.row.sale_Return_Audit_Status
                    == '1' ? "已审核" : "已驳回" }}</span>
            </template>
        </el-table-column> -->
        <el-table-column prop="customer_Name" label="客户名称" width="180px" />
        <el-table-column prop="sale_Order_Name" label="订单名称" width="180px" />
        <el-table-column prop="pro_Name" label="产品名称" width="150px" />
        <el-table-column prop="pro_Code" label="产品编号" width="180px" />
        <el-table-column prop="pro_Brand" label="品牌" width="150px" />
        <el-table-column prop="pro_Model" width="180px" label="规格型号" />
        <el-table-column prop="measure_Id" label="单位">
            <template #default="scope">
                <span>{{ measureValue(scope.row.measure_Id) }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="pro_Return_Qty" width="100px" label="退货数量" />
        <el-table-column prop="pro_Return_Price" width="100px" label="退货金额" />
        <el-table-column prop="pro_Return_Total_Qty" label="退货总数量" width="150px" />
        <el-table-column prop="pro_Return_Total_Price" width="100px" label="退货总金额" />
        <el-table-column prop="warehouse_Name" label="入库仓库" width="200px" />
    </el-table>
    <div style="height: 40px; line-height: 40px;">
        <div style="display: inline-block; float: left;">合计</div>
        <div style="display: inline-block; float:right">退货总数量：{{ return_total_qty }} &nbsp;&nbsp;&nbsp;
            退货总金额：{{
                return_total_price }}
        </div>
    </div>
    <div class="pagination-wrapper">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
            :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
</template>

<script>
import { ref, reactive, watch, onMounted, computed } from 'vue'
import axios from 'axios'
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
export default {
    props: {
        detailsData: {
            type: String,
            required: true
        },
        orderCode: String
    },
    setup(props) {
        const measureOptios = ref([])
        const tableData = ref([])
        const currentPage = ref(1)
        const pageSize = ref(5)
        const pageCount = ref(0)
        const store = useStore()
        const router = useRouter()
        const return_total_qty = computed(() => {
            return tableData.value.reduce((total, row) => {
                return total + (Number(row.pro_Return_Qty) || 0)
            }, 0)
        })
        const return_total_price = computed(() => {
            return tableData.value.reduce((total, row) => {
                return total + (Number(row.pro_Return_Price) || 0)
            }, 0)
        })

        onMounted(() => {
            getMeasure()
            fill()
            count()
        })

        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        function fill() {
            axios.get("http://localhost:5181/api/Sinv_Sale_Return/GetSinv_Sale_Return_Infos", {
                params: {
                    currentPage: currentPage.value,
                    pageSize: pageSize.value,
                    customerName: "",
                    orderCode: props.detailsData,
                    orderStatus: -1,
                    auditStatus: '1'
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                tableData.value = transformOthwrData(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        function count() {
            axios.get("http://localhost:5181/api/Sinv_Sale_Return/Sinv_Sale_ReturnCount", {
                params: {
                    customerName: "",
                    orderCode: props.detailsData
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                pageCount.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        // 数据转换方法
        const transformOthwrData = (responseData) => {
            const result = []

            responseData.forEach((mainItem) => {
                let pro_Return_Total_Qty = 0;//计算退货总数量
                mainItem.details.forEach(detail => {
                    pro_Return_Total_Qty += detail.pro_Return_Qty || 0
                })

                let pro_Return_Total_Price = 0;//计算退货总金额
                mainItem.details.forEach(detail => {
                    pro_Return_Total_Price += detail.pro_Return_Price || 0
                })
                mainItem.details.forEach((detail) => {
                    let auditStatusText = '';
                    switch (mainItem.sale_Return_Status) {
                        case 0:
                            auditStatusText = '待入库';
                            break;
                        case 1:
                            auditStatusText = '部分入库';
                            break;
                        case 2:
                            auditStatusText = '全部入库';
                            break;
                    }
                    result.push({
                        sale_Return_Audit_Status: mainItem.sale_Return_Audit_Status,
                        pro_Return_Total_Qty: pro_Return_Total_Qty,
                        sale_Return_Status: auditStatusText,
                        sale_Return_Id: mainItem.sale_Return_Id,
                        sale_Return_Code: mainItem.sale_Return_Code,
                        sale_Order_Name: mainItem.sale_Order_Name,
                        sale_Order_Code: mainItem.sale_Order_Code,
                        customer_Name: mainItem.customer_Name,
                        customer_Code: mainItem.customer_Code,
                        contacts_Name: mainItem.contacts_Name,
                        contacts_Phone: mainItem.contacts_Phone,
                        warehouse_Name: mainItem.warehouse_Name,
                        zone_Name: mainItem.zone_Name,
                        sale_Return_Reason: mainItem.sale_Return_Reason,
                        sale_Return_Store_Time: mainItem.sale_Return_Store_Time,
                        pro_Name: detail.pro_Name,
                        pro_Code: detail.pro_Code,
                        pro_Brand: detail.pro_Brand,
                        pro_Model: detail.pro_Model,
                        measure_Id: detail.measure_Id,
                        pro_Return_Qty: detail.pro_Return_Qty,
                        pro_Return_Price: detail.pro_Return_Price,
                        pro_Return_Total_Price: pro_Return_Total_Price,
                    })
                })
            })

            return result
        }

        // 合并单元格逻辑
        const objectSpanMethod = ({ row, column, rowIndex }) => {
            // 需要合并的字段
            const fieldsToMerge = [
                "sale_Return_Code",
                "customer_Name",
                "sale_Order_Code",
                "sale_Order_Name",
                "sale_Return_Status",
                "warehouse_Name",
                "pro_Return_Total_Qty",
                "action",
                "sale_Return_Audit_Status",
                "pro_Return_Total_Price"
            ];

            // 不需要合并的列直接返回
            if (!fieldsToMerge.includes(column.property)) {
                return { rowspan: 1, colspan: 1 };
            }

            // 使用订单编号作为分组依据
            const currentGroup = row.sale_Return_Code;

            // 情况1：当前行是表格第一行 或 与前一行不属于同一订单
            if (rowIndex === 0 || tableData.value[rowIndex - 1].sale_Return_Code !== currentGroup) {
                let spanCount = 1;

                // 向后查找相同订单的行数
                while (
                    rowIndex + spanCount < tableData.value.length &&
                    tableData.value[rowIndex + spanCount].sale_Return_Code === currentGroup
                ) {
                    spanCount++;
                }

                // 如果是操作列，需要特殊处理（合并所有同订单的行）
                if (column.property === 'action') {
                    return { rowspan: spanCount, colspan: 1 };
                }

                // 其他合并列检查值是否相同
                let sameValueCount = 1;
                while (
                    rowIndex + sameValueCount < tableData.value.length &&
                    tableData.value[rowIndex + sameValueCount].sale_Return_Code === currentGroup &&
                    tableData.value[rowIndex + sameValueCount][column.property] === row[column.property]
                ) {
                    sameValueCount++;
                }

                return sameValueCount > 1
                    ? { rowspan: sameValueCount, colspan: 1 }
                    : { rowspan: 1, colspan: 1 };
            }
            // 情况2：与前一行同订单且同值，需要隐藏单元格
            else if (
                tableData.value[rowIndex - 1].sale_Return_Code === currentGroup &&
                tableData.value[rowIndex - 1][column.property] === row[column.property]
            ) {
                return { rowspan: 0, colspan: 0 };
            }
            // 情况3：同订单内新值的起始位置
            else {
                let sameValueCount = 1;

                while (
                    rowIndex + sameValueCount < tableData.value.length &&
                    tableData.value[rowIndex + sameValueCount].sale_Return_Code === currentGroup &&
                    tableData.value[rowIndex + sameValueCount][column.property] === row[column.property]
                ) {
                    sameValueCount++;
                }

                return sameValueCount > 1
                    ? { rowspan: sameValueCount, colspan: 1 }
                    : { rowspan: 1, colspan: 1 };
            }
        };

        function infoPage(row) {
            store.commit("SalesReturnCode", row)
            router.push("/main/Sinv/SalesReturnInfo")
        }

        return {
            measureOptios, tableData, currentPage, pageSize, pageCount, measureValue, objectSpanMethod, infoPage, return_total_price, return_total_qty
        }
    }
}
</script>

<style scoped>
.pagination-wrapper {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    margin-top: 20px;
    /* 与表格的间距 */
}
</style>